import 'dart:io';

import 'package:path_provider/path_provider.dart';
class IoUtil{

  static Future<String> createDirectory({String dirName='stock'}) async {
    final Directory documentsDirectory = await getApplicationDocumentsDirectory();
    Directory directory = Directory('${documentsDirectory.path}${Platform.pathSeparator}$dirName');
    try {
      bool exist = await directory.exists();
      if (exist == false) {
        await directory.create();
      }
    } catch(e) {
      print("createDirectory error");
    }
    return directory.path;
  }

  //遍历文件夹下文件
  Future<Stream<FileSystemEntity>> dirList({String dirName='stock'}) async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}$dirName';
    return Directory(path).list();
  }

  //重命名文件夹名称
  _dirRename() async{
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dirName';
    var dir = Directory(path);
    var dir3= await dir.rename('${dir.parent.absolute.path}${Platform.pathSeparator}dir3');
  }

  //删除文件夹
  _deleteDir() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dir3';
    var dir = await Directory(path).delete();
  }

  //创建文件
  _createFile() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dirName${Platform.pathSeparator}file.txt';

    var file = await File(path).create(recursive: true);
  }

  //写文件
  _write2File() async{
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dirName${Platform.pathSeparator}file.txt';
    var file=File(path);
    if (file.existsSync()) {
      file.writeAsString('写入数据文件'); //写入字符串
      //file.writeAsBytes(Utf8Encoder().convert("写入数据文件"));//写入 bytes 数据
      //file.openWrite(mode: FileMode.append).write('追加到末尾'); //向末尾追加内容
    }
  }

  //读文件
  _readFile() async{
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dirName${Platform.pathSeparator}file.txt';
    var file=File(path);
    if (file.existsSync()) {
      List<String> lines = await file.readAsLines();
      for (var element in lines) {
        print(element);
      }
    }
  }

  //删除
  _deleteFile() async{
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = '${documentsDirectory.path}${Platform.pathSeparator}dirName${Platform.pathSeparator}file.txt';
    var file=File(path);
    if (file.existsSync()) {
      file.delete();
    }
  }
}